<?php

namespace App\Models\Applet\User;

use Illuminate\Support\Facades\DB;

class UserIntegralRecordsModel extends BaseUserModel
{

    protected $table = 'user_integral_records';

    const TYPE_INCREMENT = 10; // 增发
    const TYPE_DECREMENT = 20; // 扣减

    const SOURCE_TYPE_DEFAULT      = 0;  // 默认
    const SOURCE_TYPE_USER_SPONSOR = 10; // 后台认养记录发放积分
    const SOURCE_TYPE_SLAUGHTER    = 20; // 宰杀发放积分
    const SOURCE_TYPE_USE          = 30; // 使用积分

    /**
     * 列表
     * @param int $userId
     * @param array $fields
     * @return array
     */
    public function list(int $userId, array $fields = self::QUERY_DEFAULT_FIELDS): array
    {
        return $this->select($fields)
                    ->where('user_id', $userId)
                    ->where('deleted', self::DELETED_NO)
                    ->orderBy('id', 'desc')
                    ->offset((CURRENT_PAGE - 1) * PAGE_SIZE)
                    ->limit(PAGE_SIZE)
                    ->get()
                    ->toArray();
    }

    /**
     * 根据来源id查询总条数
     * @return void
     */
    public function getTotalBySourceId(array $ids, int $sourceType): array
    {
        return $this->select(['source_id', DB::raw('sum(quantity) as count')])
                    ->where('source_type', $sourceType)
                    ->whereIn('source_id', $ids)
                    ->where('deleted', self::DELETED_NO)
                    ->groupBy('source_id')
                    ->get()
                    ->toArray();
    }

    /**
     * 根据用户id和来源id删除
     * @return void
     */
    public function deleteItemByUserIdAndSourceId(int $userId, int $sourceId)
    {
        $this->where('user_id', $userId)
             ->where('source_id', $sourceId)
             ->where('deleted', self::DELETED_NO)
             ->update([
                 'deleted' => self::DELETED_YES,
             ]);
    }
}
